//
//  ProductDetailsViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/26.
//

import UIKit

class ProductDetailsViewController: BaseViewController {
    var id = 0
    var collectBtn: UIButton!
    var bgBavView: UIView!
    var tableView: BaseTableView!
    var addShoppingCarBtn: UIButton!
    var carNumLab: UILabel!//购物车数量
    var cartNum = 0//商品在购车的数量
    var detailModel: DetailModel!
    var detailDataModel: ProductDetailDataModel!
//    var promotionFlag: Bool = false //是否限时抢购
    var bottomView: UIView = {
       let tempView = UIView()
        tempView.backgroundColor = .white
        return tempView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.barBackgroundColor = .clear
        self.navBar.isHidden = true
        self.initTableView()
        self.addInitNav()//要放在表的下面要不开始进来久看不到返回按钮等
        self.initTabbarBtn()
        self.requestGetProductDetail()
        //限时抢购结束
        NotificationCenter.default.addObserver(self, selector: #selector(roadRefreash), name: NSNotification.Name("mainRefreash"), object: nil)
    }
    
    
     deinit {
         NotificationCenter.default.removeObserver(self)
     }
    
    //导航栏
    func addInitNav() {
        
        self.bgBavView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: NavBarHight))
        self.bgBavView.backgroundColor = UIColor.init(hex: 0xFFFFFF, alpha: 0)
        self.view.addSubview( self.bgBavView)
        
        
        let backBtn = UIButton.init(frame: CGRect.init(x: 14, y: NavBarHight - 34, width: 24, height: 24))
        backBtn.backgroundColor = UIColor(hex: 0x000000 ,alpha: 0.6)
        backBtn.layer.cornerRadius = 12
        backBtn.clipsToBounds = true
        backBtn.setImage(UIImage.init(named: "icon_vehicle_nav_back"), for: .normal)
        backBtn.setImage(UIImage.init(named: "icon_vehicle_nav_back"), for: .highlighted)
        backBtn.addTarget(self, action: #selector(backBtnAction), for: .touchUpInside)
        self.bgBavView.addSubview(backBtn)
        
        
        //kScreenWidth - 104
        let shareBtn = UIButton(frame: CGRect(x: kScreenWidth - 38, y: NavBarHight - 34, width: 24, height: 24))
        shareBtn.backgroundColor = UIColor(hex: 0x000000 ,alpha: 0.6)
        shareBtn.layer.cornerRadius = 12
        shareBtn.clipsToBounds = true
        shareBtn.setImage(UIImage(named: "icon_normal_white_share"), for: .normal)
        shareBtn.setImage(UIImage(named: "icon_normal_white_share"), for: .selected)
        shareBtn.addTarget(self, action: #selector(shareBtnAntion(sender:)), for: .touchUpInside)
        shareBtn.isHidden = false
        self.bgBavView.addSubview(shareBtn)
        
        //kScreenWidth - 74
        self.collectBtn = UIButton(frame: CGRect(x: kScreenWidth - 76, y: NavBarHight - 34, width: 24, height: 24))
        collectBtn.backgroundColor = UIColor(hex: 0x000000 ,alpha: 0.6)
        collectBtn.layer.cornerRadius = 12
        collectBtn.clipsToBounds = true
        self.collectBtn.setImage(UIImage(named: "icon_vehicle_normal_c"), for: .normal)
        self.collectBtn.setImage(UIImage(named: "icon_vehicle_select_c"), for: .selected)
        self.collectBtn.addTarget(self, action: #selector(collectBtnAntion), for: .touchUpInside)
        self.collectBtn.isHidden = true
        self.bgBavView.addSubview(self.collectBtn)
    }
    
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - TabbarHeight), style: .grouped)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = .white
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.register(ProductImageTableViewCell.self, forCellReuseIdentifier: "ProductImageTableViewCell")
        self.tableView.register(ProductPriceTableViewCell.self, forCellReuseIdentifier: "ProductPriceTableViewCell")
        self.tableView.register(ProductInfoTableViewCell.self, forCellReuseIdentifier: "ProductInfoTableViewCell")//基础参数
        self.tableView.register(DescribeTableViewCell.self, forCellReuseIdentifier: "DescribeTableViewCell")
        self.view.addSubview(self.tableView)
        
    }
    
    //购物车
    func initTabbarBtn() {
        let tempH: CGFloat = IphoneXMarginBottom + 50 + (IphoneXMarginBottom > 1 ? 0 : 4)
        self.bottomView.frame = CGRect.init(x: 0, y: kScreenHeight - tempH, width: kScreenWidth, height: tempH)
        self.view.addSubview(self.bottomView)
        
        let shoppingCarBtn = UIButton(frame: CGRect(x: 14, y: 4, width: 77, height: 46))
        shoppingCarBtn.setImage(UIImage(named: "icon_goods_shopping"), for: .normal)
        shoppingCarBtn.addTarget(self, action: #selector(shoppingCarBtnAntion), for: .touchUpInside)
        bottomView.addSubview(shoppingCarBtn)
        
        
        self.carNumLab = UILabel(frame: CGRect(x: shoppingCarBtn.width - 27, y: 5, width: 16, height: 12))
        self.carNumLab.backgroundColor = Theme.redColor
        self.carNumLab.layer.cornerRadius = 6
        self.carNumLab.layer.masksToBounds = true
        self.carNumLab.textColor = .white
        self.carNumLab.textAlignment = .center
        self.carNumLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 13)
        self.carNumLab.adjustsFontSizeToFitWidth = true
        self.carNumLab.minimumScaleFactor = 0.6
        self.carNumLab.isHidden = true
        shoppingCarBtn.addSubview(self.carNumLab)
        
        
        self.addShoppingCarBtn = UIButton(frame: CGRect(x: shoppingCarBtn.right + 10, y: 4, width: kScreenWidth - 38 - shoppingCarBtn.width, height: 46))
        self.addShoppingCarBtn.addTarget(self, action: #selector(addShoppingCarBtnAntion), for: .touchUpInside)
        self.addShoppingCarBtn.setTitle(MMLocalizedString("add_shoppingCar", comment: "加入购物车"), for: .normal)
        self.addShoppingCarBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.addShoppingCarBtn.setTitleColor(.white, for: .normal)
        self.addShoppingCarBtn.backgroundColor = Theme.mainColor
        self.addShoppingCarBtn.layer.cornerRadius = 8
        self.addShoppingCarBtn.layer.masksToBounds = true
        bottomView.addSubview(self.addShoppingCarBtn)

    }
    
    
    
    //MARK: - Requset
    //商品详情
    func requestGetProductDetail(){
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getProductDetail(param: ["id": "\(self.id )"]), objectType: ProductDetailModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! ProductDetailModel
            if resultObj.code == "1" {
                self.detailDataModel = (resultObj.data?.data)
                self.detailDataModel.parameters = resultObj.data?.parameters//规格
                self.detailModel = resultObj.data
                let isTime = self.detailDataModel.isLimitedTime ?? 0
                if isTime != 1 {
                    self.collectBtn.isHidden = false
                }else{
                    self.collectBtn.isHidden = true
                }
                //是否收藏
                if self.detailDataModel?.isFavorite == true {
                    self.collectBtn.isSelected = true
                }else{
                    self.collectBtn.isSelected = false
                }
                
                let skuArray = self.detailDataModel?.skuDTOList ?? []//默认取第一个sku
                var skuModel = SkuDTOListModel.init()
                if skuArray.count > 0{
                    skuModel = skuArray[0]
                }
                if (skuModel.availableStock ?? 0 == 0) || (self.detailDataModel.isValid ?? false == false){//没库存,失效商品
                    self.addShoppingCarBtn.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.3)
                    self.addShoppingCarBtn.isUserInteractionEnabled = false
                 }else{
                    self.addShoppingCarBtn.backgroundColor = Theme.mainColor
                    self.addShoppingCarBtn.isUserInteractionEnabled = true
                }
                self.requestGetCurrentNum()
                
                //block 选择规格
                self.detailDataModel.selectSpecificationBlock = {[weak self] in
                    self?.addShoppingCarBtnAntion()
                }
                
                
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
            self.tableView.reloadData()
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    
    //收藏取消收藏
    func requestFavorite(){
        let param = ["productId": "\(self.detailDataModel.id ?? 0)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.favoriteProduct(param: param),objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                if self.detailDataModel?.isFavorite == false{
                    self.view.makeToast(message: MMLocalizedString("successful_collection", comment: "收藏成功"))
                }else{
                    self.view.makeToast(message: MMLocalizedString("uncollected", comment: "已取消收藏"))
                }
                //延迟
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    self.requestGetProductDetail()
                }
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        }error: { err in
            
        }
    }
    
    //查询当前商品购物车数量
    func requestGetCurrentNum(){
        var param = NSMutableDictionary() as! [String: Any]
        //单规格的时候默认取第一
        let skuArray = self.detailDataModel?.skuDTOList ?? []
        if skuArray.count == 0 {
            self.carNumLab.isHidden = true
            return
        }
        let skuModel = skuArray[0]
        param["skuId"] = "\(skuModel.id ?? 0)"
        if UserModule.shared.isLogined ?? false == false {  //未登录
            param["cartKey"] = XTManageCenter.getLocalStringDataValue(aKey: XTManageCenter.CartKey)
        }
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getCurrentNum(param: param), objectType: AddShopingCartModel.self) { data in
            let resultObj = data as! AddShopingCartModel
            if resultObj.code == "1" {
                let model = resultObj.data
                self.cartNum = model?.num ?? 0
                if self.cartNum == 0{
                    self.carNumLab.isHidden = true
                }else{
                    self.carNumLab.isHidden = false
                    self.carNumLab.text = "\(self.cartNum)"
                }
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    
    //购物车添加商品
    func requestAddShopingCart(){
        var param = NSMutableDictionary() as! [String: Any]
        //单规格的时候默认取第一
        let skuArray = self.detailDataModel?.skuDTOList ?? []
        if skuArray.count == 0 {
           return
        }
        let skuModel = skuArray[0]
        param["skuId"] = "\(skuModel.id ?? 0)"
        param["quantity"] = "\(self.cartNum + 1)"
        if UserModule.shared.isLogined ?? false == false {  //未登录
            param["cartKey"] = XTManageCenter.getLocalStringDataValue(aKey: XTManageCenter.CartKey)
        }
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.addShoppingCart(param: param), objectType: AddShopingCartModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! AddShopingCartModel
            if resultObj.code == "1" {
                let model = resultObj.data
                XTManageCenter.setLocalDataString(aKey: XTManageCenter.CartKey, aValue: model?.cartKey ?? "")
                self.view.makeToastBottom(message: MMLocalizedString("add_cart", comment: "加入购物车成功"))
                self.requestGetCurrentNum()
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    
    
    
    //MARK: - Antion
    
    func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }
    
    @objc func backBtnAction() {
        self.navigationController?.popViewController(animated: true)
    }
    

    //收藏
    @objc func collectBtnAntion() {
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        if self.detailDataModel == nil{
            return
        }
        
        self.requestFavorite()
    }
    

    //分享
    @objc func shareBtnAntion(sender: UIButton) {
        let VC = ShareViewController()
        VC.titleStr = MMLocalizedString("share", comment: "分享")
        VC.shareContent = self.detailDataModel?.shareText ?? ""
        VC.shareUrl = self.detailDataModel?.shareText ?? ""
        VC.modalPresentationStyle = .overFullScreen
        self.present(VC, animated: false, completion: nil)
    }
    
    //购物车
    @objc func shoppingCarBtnAntion() {
        let vc = ShoppingCarViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //加入购物车
    @objc func addShoppingCarBtnAntion() {
        if (self.detailModel?.parameters ?? []).count > 0 {//多规格
            let vc = ProductPecSheetViewController()
            vc.modalPresentationStyle = .overFullScreen
            if self.detailModel != nil {
                vc.detailModel = self.detailModel
            }
            self.present(vc, animated: false, completion: nil)

            vc.hiddenActionViewBlock = { [weak self] in
                self?.requestGetCurrentNum()
            }
        }else {
           self.requestAddShopingCart()//单品直接加入购物车
        }
    }
    
    //刷新
    @objc func roadRefreash(){
        self.requestGetProductDetail()
    }
    

}

extension ProductDetailsViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if self.detailDataModel?.productDecr ?? "" == "" && indexPath.section == 4{
            return 0.01
        }
 
        return UITableViewAutomaticDimension
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProductImageTableViewCell", for: indexPath) as! ProductImageTableViewCell
            if self.detailDataModel != nil{
                cell.setModel(model: self.detailDataModel)
            }
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProductPriceTableViewCell", for: indexPath) as! ProductPriceTableViewCell
            if self.detailDataModel != nil{
                cell.dataModel(model: self.detailDataModel)
            }
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProductInfoTableViewCell", for: indexPath) as! ProductInfoTableViewCell
            if self.detailDataModel != nil{
                cell.setModel(model: self.detailDataModel)
            }
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "DescribeTableViewCell", for: indexPath) as! DescribeTableViewCell
            if self.detailDataModel != nil{
                cell.setProductDecrModel(productDecrModel: self.detailDataModel)
            }
            
//            cell.webViewHeightBlock = { [weak self ](height: CGFloat) in
//                self?.tableView.reloadData()
//            }
            
            return cell
            
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let bgView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .white
        return bgView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .clear
        return bgView
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.y
        //naviBar透明度
        let pre = 375.0/375 as CGFloat
        let bannerH = (kScreenWidth * pre) - NavBarHight
        if offset <= 0 {
            self.bgBavView.backgroundColor = UIColor.init(hex: 0xffffff, alpha: 0)
        }else{
            let tempAlpha = offset/bannerH
            self.bgBavView.backgroundColor = UIColor.init(hex: 0xffffff, alpha: tempAlpha)
        }

        //把self.bgBavView拿到上面
        self.view.bringSubview(toFront: self.bgBavView)
    }
}
